import 'dart:io';

/// 连接重试配置
class RetryConfig {
  /// 最大重试次数
  final int maxRetries;
  
  /// 初始延迟时间（秒）
  final int initialDelaySeconds;
  
  /// 最大延迟时间（秒）
  final int maxDelaySeconds;
  
  /// 退避乘数
  final double backoffMultiplier;
  
  /// 连接超时时间（秒）
  final int connectionTimeoutSeconds;
  
  /// 是否启用重试
  final bool enabled;

  const RetryConfig({
    this.maxRetries = 5,
    this.initialDelaySeconds = 1,
    this.maxDelaySeconds = 30,
    this.backoffMultiplier = 2.0,
    this.connectionTimeoutSeconds = 10,
    this.enabled = true,
  });

  /// 从环境变量创建配置
  factory RetryConfig.fromEnvironment() {
    return RetryConfig(
      maxRetries: int.tryParse(Platform.environment['RETRY_MAX_RETRIES'] ?? '5') ?? 5,
      initialDelaySeconds: int.tryParse(Platform.environment['RETRY_INITIAL_DELAY'] ?? '1') ?? 1,
      maxDelaySeconds: int.tryParse(Platform.environment['RETRY_MAX_DELAY'] ?? '30') ?? 30,
      backoffMultiplier: double.tryParse(Platform.environment['RETRY_BACKOFF_MULTIPLIER'] ?? '2.0') ?? 2.0,
      connectionTimeoutSeconds: int.tryParse(Platform.environment['RETRY_CONNECTION_TIMEOUT'] ?? '10') ?? 10,
      enabled: Platform.environment['RETRY_ENABLED']?.toLowerCase() != 'false',
    );
  }

  /// 默认配置
  static const RetryConfig defaultConfig = RetryConfig();

  /// 快速重试配置（用于测试）
  static const RetryConfig fastConfig = RetryConfig(
    maxRetries: 3,
    initialDelaySeconds: 1,
    maxDelaySeconds: 5,
    backoffMultiplier: 1.5,
    connectionTimeoutSeconds: 5,
  );

  /// 慢速重试配置（用于网络不稳定环境）
  static const RetryConfig slowConfig = RetryConfig(
    maxRetries: 10,
    initialDelaySeconds: 2,
    maxDelaySeconds: 60,
    backoffMultiplier: 2.5,
    connectionTimeoutSeconds: 15,
  );

  /// 禁用重试配置
  static const RetryConfig disabledConfig = RetryConfig(
    enabled: false,
  );

  @override
  String toString() {
    return 'RetryConfig{maxRetries: $maxRetries, initialDelay: ${initialDelaySeconds}s, maxDelay: ${maxDelaySeconds}s, backoff: $backoffMultiplier, timeout: ${connectionTimeoutSeconds}s, enabled: $enabled}';
  }
}
